package cn.xm.pet.service.impl;


import cn.xm.pet.domain.PetType;
import cn.xm.pet.mapper.PetTypeMapper;
import cn.xm.pet.service.PetTypeService;
import cn.xm.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xm
 * @since 2022-10-30
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements PetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;
    
    @Override
    public List<PetType> petTree() {
        List<PetType> petTypes = petTypeMapper.findAll();
        Map<Long, PetType> parentMap = petTypes.stream().collect(Collectors.toMap(PetType::getId, petType -> petType));
        List<PetType> result = new ArrayList<>();
        for (PetType petType:
                petTypes) {
            if (petType.getPid() == null) {
                result.add(petType);
            } else {
                PetType parent = parentMap.get(petType.getPid());
                List<PetType> children = parent.getChildren();
                children.add(petType);
//                for (PetType parent:
//                     petTypes) {
//                    if (parent.getId().equals(dept.getParentId())) {
//                        parent.getChildren().add(dept);
//                        break;
//                    }
//                }
            }
        }
        return result;
    }
}
